package com.papercutting.platform.config;

import com.papercutting.platform.filter.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/**
 * 安全配置类
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .cors().and()
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeHttpRequests(authz -> authz
                .requestMatchers(
                    new AntPathRequestMatcher("/api/auth/**"),
                    new AntPathRequestMatcher("/api/health"),
                    new AntPathRequestMatcher("/api/info"),
                    new AntPathRequestMatcher("/uploads/**"),
                    new AntPathRequestMatcher("/images/**"),
                    new AntPathRequestMatcher("/static/**"),
                    new AntPathRequestMatcher("/error"),
                    new AntPathRequestMatcher("/api/banner/active"),
                    new AntPathRequestMatcher("/api/carousel/**"),
                    new AntPathRequestMatcher("/api/home/**"),
                    new AntPathRequestMatcher("/api/culture/**"),
                    new AntPathRequestMatcher("/api/tutorial/**"),
                    new AntPathRequestMatcher("/api/tutorial-step/**"),
                    new AntPathRequestMatcher("/api/news/**"),
                    new AntPathRequestMatcher("/api/search/**"),
                    new AntPathRequestMatcher("/api/ai/**")
                ).permitAll()
                .requestMatchers(
                    new AntPathRequestMatcher("/api/banners/**")
                ).hasRole("ADMIN")
                .anyRequest().authenticated()
            )
            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        
        return http.build();
    }
}